package cn.lili.util;

import cn.lili.modules.distribution.entity.vos.HomeResult;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.List;

/**
 * 首页统计工具类
 */
public class HomeResultUtil {

    /**
     * 组装数据接口
     *
     * @param collection    集合
     * @param dateExtractor 创建时间
     * @return 组装数据结果
     */
    public static <T> HomeResult createResult(List<T> collection, DateExtractor<T> dateExtractor) {
        HomeResult homeResult = new HomeResult();
        // 总数量统计
        homeResult.setCount((long) collection.size());
        // 本月数量统计
        long currentMonthCount = collection.stream().filter(item -> {
            LocalDate createDate = dateExtractor.extractDate(item);
            return createDate.getMonth() == LocalDate.now().getMonth();
        }).count();
        homeResult.setMonthCount(currentMonthCount);
        // 本周数量统计
        LocalDate startOfWeek = LocalDate.now().with(DayOfWeek.MONDAY);
        long currentWeekCount = collection.stream().filter(item -> {
            LocalDate createDate = dateExtractor.extractDate(item);
            return !createDate.isBefore(startOfWeek) && !createDate.isAfter(LocalDate.now());
        }).count();
        homeResult.setThisWeekCount(currentWeekCount);
        // 今日数量统计
        long todayCount = collection.stream().filter(item -> {
            LocalDate createDate = dateExtractor.extractDate(item);
            return createDate.isEqual(LocalDate.now());
        }).count();
        homeResult.setTodayCount(todayCount);
        return homeResult;
    }

    /**
     * 创建默认值对象
     *
     * @return 默认值
     */
    public static HomeResult createDefaultValue() {
        HomeResult homeResult = new HomeResult();
        homeResult.setCount(0L);
        homeResult.setMonthCount(0L);
        homeResult.setThisWeekCount(0L);
        homeResult.setTodayCount(0L);
        homeResult.setViolationThisMonthCount(0L);
        return homeResult;
    }

    public interface DateExtractor<T> {
        LocalDate extractDate(T item);
    }
}
